<!--本组件最小宽度为600，最佳显示宽度为620px-820px-->

<!--【回调函数】-->
<!--音频加载完成时的回调函数：audioPreparedCallBack-->
<!--音频当前播放时间变化时的回调函数：currentTimeChangeCallBack-->
<template>
  <div class="audioPlayer">
    <!--被隐藏显示的真实音频控件-->
    <audio
      @error="handleAudioError"
      ref="audioNode"
      @ended="pausePlayAudio"
      @timeupdate="onAudioTimeupdate"
      @loadedmetadata="onAudioLoadedmetadata"
      controls
      style="height: 0px;display:none"
    >
      <source :src="audioSrc" />
    </audio>
    <!-- 1.音频进度 -->
    <div class="audioBarBlock">
      <!--1.2 进度滑块  -->
      <el-slider
        class="audioBarSlider"
        v-model="audioControlData.currentAudioTimeFromSlider"
        :format-tooltip="audioProcessToolTipFormat"
        @input="changeCurrentTime"
      ></el-slider>
    </div>
    <!-- 2.音频控制按钮 -->
    <div class="playBtnArea">
      <!-- 2.1 时间 -->
      <div class="playTime">
        <!-- 1.1 当前播放时间 -->
        <div class="currentPlayTime">{{ audioControlData.currentAudioTimeForDisplay }}</div>
        <!-- 1.3 音频总时间 -->
        <div class="totalPlayTime">
          /
          {{
            audioControlData.audioTotalTimeForDisplay === 0
              ? '0:00:00'
              : audioControlData.audioTotalTimeForDisplay
          }}
        </div>
      </div>

      <!-- 2.2 开始/暂停/ 快进/快退 -->
      <div class="opBtnArea">
        <div class="backBtn" @click="jumpTime('l')">
          <el-icon><CaretLeft /><CaretLeft /></el-icon>
        </div>
        <div class="pausePlay">
          <div class="playBtn" v-if="!audioControlData.isPlayAudio" @click="startPlayAudio"></div>
          <div class="pauseBtn" v-else @click="pausePlayAudio"></div>
        </div>
        <div class="aheadBtn" @click="jumpTime('r')">
          <el-icon><CaretRight /><CaretRight /></el-icon>
        </div>
      </div>

      <!-- 2.3  -->
      <div class="volumeAndQuickPlay">
        <!-- 2.3.1 音量 -->
        <div class="volumeArea">
          <div style="line-height: 28px; color: #1c9d6d">
            <!-- 音量 -->
            <!-- 静音 -->
            <img v-show="isMute" 
            style="width:18px;height:18px"
            src="@/assets/my_content/mute.png"
              @click="changeMute(50)"
           >
            <!-- 非静音 -->
           <img
              v-show="!isMute"
              src="@/assets/my_content/3.png"
              @click="changeMute(0)"
            />
          </div>
          <div style=""  class="volume">
            <el-slider
              v-model="volumeNum"
              :show-tooltip="false"
              vertical
              height="100px"
              
            ></el-slider>
          </div>
        </div>
        <!-- 2.3.2 倍速 -->
        <div class="quickPlayArea">
          <el-dropdown placement="top" @command="changeSpeed">
            <span class="el-dropdown-link" style="cursor: pointer;color: rgba(64, 64, 64, 1);">
               {{ Number(currentSpeed).toFixed(1) ? Number(currentSpeed).toFixed(2) :1.0 }}&times;
            </span>
            <!-- <span class="el-dropdown-link" style="cursor: pointer">
              倍速 -->
              <!-- <el-icon class="el-icon--right">
                <arrow-down />
              </el-icon> -->
            <!-- </span> -->
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item command="0.5">0.5&times;</el-dropdown-item>
                <el-dropdown-item command="0.75">0.75&times;</el-dropdown-item>
                <el-dropdown-item command="1.0">1.0&times;</el-dropdown-item>
                <el-dropdown-item command="1.5">1.5&times;</el-dropdown-item>
                <el-dropdown-item command="2.0">2.0&times;</el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </div>
      </div>
    </div>
  </div>
</template>
<script setup>
import { ref,  watch, defineEmits,onBeforeUnmount ,nextTick} from 'vue'
import {
  CaretLeft,
  CaretRight
} from '@element-plus/icons-vue'
import {
  ElMessage,
  ElMessageBox,
  
} from 'element-plus'
const isShowVolume = ref(false)

const props = defineProps({
  // 音频路径
  audioSrc: String,
  currentTime: Number
})

// 2、定义发射给父组件的方法
const emits = defineEmits(['currentTimeChangeCallBack', 'audioPreparedCallBack'])

const audioNode = ref('')
// 音量大小
const volumeNum = ref(50)

const isMute=ref(false)
const changeMute=(v)=> {
  // debugger
  // isShowVolume.value =true
  volumeNum.value=v
}
// 当前播放倍速
const currentSpeed = ref(1.0)
const audioControlData = ref({
  // 音频时长
  fileTime: 0,
  // 音频当前播放时间(控制条滑块绑定)
  currentAudioTimeFromSlider: 0,
  // 音频当前播放时间(显示使用)
  currentAudioTimeForDisplay: 0,
  // 音频总时长(显示使用)
  audioTotalTimeForDisplay: 0,
  // 音频当前播放时间
  currentAudioTime: 0,
  // 当前播放状态
  isPlayAudio: false
})
// 重置状态
const resetStatus = () => {
  audioControlData.value.fileTime = 0
  audioControlData.value.currentAudioTimeFromSlider = 0
  audioControlData.value.currentAudioTimeForDisplay = 0
  audioControlData.value.audioTotalTimeForDisplay = 0
  audioControlData.value.currentAudioTime = 0
  audioControlData.value.isPlayAudio = false
}
watch(
  () => props.audioSrc,
  () => {
    // debugger
    // audioNode.value.src = nVal
    resetStatus()
  }
)
watch(
  () => props.currentTime,
  () => {
    //  debugger
    audioNode.value.currentTime = Number(props.currentTime)
  }
)
watch(
  () => volumeNum.value,
  () => {
    audioNode.value.volume = Number(volumeNum.value) / 100
    if(volumeNum.value>0){
      // debugger
      isMute.value=false
    }else{
      isMute.value=true
    }
  }
)

// 音频播放条显示格式化
const audioProcessToolTipFormat = (index = 0) => {
  index = Number((audioControlData.value.fileTime / 100) * index).toFixed(0)
  audioControlData.value.currentAudioTimeForDisplay = formatSecondToHms(index)
  return audioControlData.value.currentAudioTimeForDisplay
}
const formatSecondToHms = (second) => {
  // -------------------------内置时间格式化------------------------
  // 将秒数转化为0:00:00的格式
  const secondType = typeof second
  if (secondType === 'number' || secondType === 'string') {
    second = parseInt(second)
    const hours = Math.floor(second / 3600)
    second = second - hours * 3600
    const mimute = Math.floor(second / 60)
    second = second - mimute * 60
    return hours + ':' + ('0' + mimute).slice(-2) + ':' + ('0' + second).slice(-2)
  } else {
    return '0:00:00'
  }
}
// 音频播放条拖动(改变当前播放时间)
const changeCurrentTime = (index) => {
  audioControlData.value.currentAudioTime = Number(
    (index / 100) * audioControlData.value.fileTime
  ).toFixed(0)
  audioNode.value.currentTime = audioControlData.value.currentAudioTime
}

// 点击播放按钮
const startPlayAudio = () => {
  // 判断是否支持播放
  // 获取音频时长失败的话说明该音频不支持播放
  // console.log(audioControlData.value.fileTime)
  if (audioControlData.value.fileTime && audioControlData.value.fileTime !== 0) {
    // 显示播放中按钮
    audioControlData.value.isPlayAudio = true
    // 开始播放音频
    audioNode.value.play()
  } else {
    ElMessageBox.confirm('解析音频数据失败，暂不支持播放该音频！', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
      .then(() => {})
      .catch(() => {})
  }
}
// 点击暂停播放按钮
const pausePlayAudio = () => {
  // 显示暂停中按钮
  audioControlData.value.isPlayAudio = false
  // 暂停播放音频
  audioNode.value.pause()
}

const spaceEventFn=function(event){
  if(event.keyCode==32  ){
      console.log('空格键被按下')
    if(audioControlData.value.isPlayAudio == false || audioControlData.value.isPlayAudio!=true){
      
      startPlayAudio()
    }else{
      pausePlayAudio()
    }  
  }
}
//空格键 
window.addEventListener('keydown',spaceEventFn)

onBeforeUnmount(()=>{
    window.removeEventListener("keydown",spaceEventFn)
    
})

// -------------------实际音频控件回调函数----------------------
// 音频播放时的音频当前播放时间
const onAudioTimeupdate = (audioNode) => {
  // debugger
  // 动态更新音频条进度
  audioControlData.value.currentAudioTimeFromSlider =
    (parseInt(audioNode.target.currentTime) / audioControlData.value.fileTime) * 100
  // 同时向父组件传递当前音乐播放的时间
  emits('currentTimeChangeCallBack', { audioTime: Number(audioNode.target.currentTime) })
}
// 音频资源及音频信息加载完成后的回调函数
const onAudioLoadedmetadata = (audio) => {
  audioControlData.value.fileTime = Number(audio.target.duration).toFixed(0)
  audioControlData.value.audioTotalTimeForDisplay = formatSecondToHms(audio.target.duration)
  // 同时设置默认音量为系统允许音量的50%
  audioNode.value.volume = 0.5
  // 同时向父组件传递当前音频信息
  emits('audioPreparedCallBack', audio)
 
}
// ---------------------前进后退，音量，倍速
// 前进/后退
const jumpTime = (type) => {
  // 后退15s
  if (type === 'l') {
    audioNode.value.currentTime -= 15
  } else {
    // 前进15s
    audioNode.value.currentTime += 15
  }
}
// 倍速
const changeSpeed = (ev) => {
  currentSpeed.value = Number(ev)
  audioNode.value.playbackRate = ev
}

defineExpose({
  startPlayAudio,
  onAudioLoadedmetadata

})

const handleAudioError=() =>{
  pausePlayAudio()
  // 在这里处理音频资源加载失败的逻辑
  console.log('播放错误，请检查网络！')
  ElMessage({
    message: '播放错误，请检查网络！',
    type: 'error',
    duration:0,
    showClose:true
  })
  
}



</script>

<style scoped lang="less">
.audioPlayer {
  width: 100%;
  // height: 100px;
  height: 82px;
  box-sizing: border-box;
  background-color: rgba(247, 247, 247, 1);
  display: flex;
  flex-direction: column;
  justify-content: flex-start;
  flex: none;

  // 1.音频进度
  .audioBarBlock {
    box-sizing: border-box;
    // margin-top: -26px;
    margin-left: 14px;
    margin-right: 14px;

    :v-deep(.audioBarSlider) {
      height: 36px;
      flex-grow: 1;

      .el-slider__runway {
        height: 4px;
        background-color: #cccccc;

        .el-slider__bar {
          height: 4px;
          background-color: #1c9d6d;
        }

        .el-slider__button-wrapper {
          width: 16px;
          height: 16px;
          top: -7px;

          .el-slider__button {
            width: 8px;
            height: 8px;
            background-color: #1c9d6d;
            border-color: #1c9d6d;
          }
        }
      }
    }
  }
  // 2.音频控制按钮
  .playBtnArea {
    // width: 100%;
    // height: 70px;
    position: relative;
    display: flex;
    justify-content: space-between;
    align-items: center;

    margin-left: 14px;
    margin-right: 14px;
    // 2.1播放时长/总时长
    .playTime {
      display: flex;

      .currentPlayTime {
        padding-right: 2px;

        box-sizing: border-box;
        height: 20px;

        text-align: center;
        font-size: 14px;
        color: #52abfd;
        line-height: 20px;
        font-weight: 500;
      }
      .totalPlayTime {
        height: 20px;
        box-sizing: border-box;
        font-size: 14px;
        text-align: center;
        color: #949494;
        line-height: 20px;
        font-weight: 500;
      }
    }

    // 2.2中心播放/暂停按钮、前进/后退15s按钮
    .opBtnArea {
      width: 160px;
      margin: 0 auto;
      display: flex;
      justify-content: space-between;
      align-items: center;
      .backBtn {
        width: 70px;
        height: 32px;
        line-height: 32px;
        text-align: center;
        cursor: pointer;
        color: #1c9d6d;

        &:hover {
          font-size: 16px;
        }

        .el-icon {
          width: 24px;
          height: 24px;
          svg {
            // width: 12px;
            // height: 12px;
            color: black;
            margin-left: -8px;
          }
        }
      }

      .pausePlay {
        // margin-top: -10px;
        .playBtn {
          width: 32px;
          height: 32px;
          border-radius: 50%;
          background: url('@/assets/my_content/zanting.jpg') no-repeat;
          background-size: contain;

          &:hover {
            transform: scale(1.1);
            cursor: pointer;
          }
        }
        .pauseBtn {
          width: 32px;
          height: 32px;
          background: url('@/assets/my_content/bofang.png') no-repeat;

          background-size: contain;

          &:hover {
            transform: scale(1.1);
            cursor: pointer;
          }
        }
      }

      // 快进
      .aheadBtn {
        width: 70px;
        height: 32px;
        line-height: 32px;
        text-align: center;
        cursor: pointer;
        color: #1c9d6d;

        &:hover {
          font-size: 16px;
        }

        .el-icon {
          width: 24px;
          height: 24px;
          svg {
            // width: 12px;
            // height: 12px;
            color: black;
            margin-right: -8px;
          }
        }
      }
    }
    // 2.3 音量/倍速
    .volumeAndQuickPlay {
      display: flex;
      justify-content: flex-start;
      align-items: center;
      // 音量区域
      .volumeArea {
        // width: 120px;
        display: flex;
        align-items: center;
        & > div:nth-child(1) {
          img {
            margin-top: 11px;
          }
        }
        .volume {
          display: none;
          position: absolute;
          bottom: 28px;
          right: 88px;
        }
        &:hover {
          .volume {
            position: absolute;
            bottom: 33px;
            right: 88px;
            display: inline-block;
          }
        }
        :v-deep(.el-slider) {
          .el-slider__runway {
            height: 4px;
            background-color: #dedede;
            margin: 12px 0;

            .el-slider__bar {
              height: 4px;
              background-color: #1c9d6d;
            }

            .el-slider__button-wrapper {
              width: 16px;
              height: 16px;
              top: -7px;

              .el-slider__button {
                width: 8px;
                height: 8px;
                background-color: #1c9d6d;
                border-color: #1c9d6d;
              }
            }
          }
        }
      }
      // 倍速播放区域
      .quickPlayArea {
        width: 50px;
        margin-left: 24px;
        margin-right: 24px;
        display: flex;
        color: rgba(64, 64, 64, 1);
        font-size: 14px;
        text-align: left;
        font-family: SourceHanSansSC-regular;
        :v-deep(.el-dropdown) {
          .el-dropdown-link {
            line-height: 30px;
            color: #1c9d6d;
            border: 1px solid #1c9d6d;
            padding: 2px 5px;
            border-radius: 15px;

            &:hover {
              // font-weight: 600;
              border: 0px;
              box-shadow: none;
            }
          }
        }
      }
    }
  }
}
</style>
